<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 顶部添加按钮区域 -->
      <el-button type="primary">添加按钮</el-button>
      <el-table :data="userList" style="width: 100%" border stripe>
        <!-- 用于显示展开列的显示权限 -->
        <el-table-column type="expand" width="180">
          <template slot-scope="scope">
            <!-- 渲染一级权限 -->
            <el-row v-for="(item, index) in scope.row.children" :key="index" :class="['center']">
              <el-col :span="5">
                <el-tag closable @close="removeTag(scope.row, item.id)">{{ item.authName }}</el-tag>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row v-for="item1 in item.children" :key="item1.id" :class="['center']">
                  <el-col :span="12">
                    <el-tag closable type="success" @close="removeTag(scope.row, item1.id)">{{
                      item1.authName
                    }}</el-tag>
                  </el-col>
                  <el-col :span="12">
                    <el-tag
                      type="warning"
                      closable
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      @close="removeTag(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="180"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="180"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="assignRights(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="assignVisible" width="50%" @close="assignClosed">
      <el-tree
        :default-checked-keys="checkedKeys"
        show-checkbox
        :data="rightsList"
        node-key="id"
        default-expand-all
        :props="treeProps"
        ref="treeref"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAssign">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: [],
      assignVisible: false,
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      checkedKeys: [],
      currentRoleId: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.$message.success('获取用户数据成功')
      this.userList = res.data
    },

    //删除三级权限
    async removeTag(role, id) {
      const res = await this.$confirm('您确认要删除该权限吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err)

      if (res !== 'confirm') return this.$message.info('取消了删除')
      console.log(id)
      const { data: res1 } = await this.$http.delete(`roles/${role.id}/rights/${id}`)
      if (res1.meta.status !== 200) return this.$message.error('删除角色权限失败')
      console.log(res1)

      //删除成功后把从服务器返回来的新数组替代以前的旧数组
      role.children = res1.data
    },

    //展示分配权限面板
    async assignRights(role) {
      this.currentRoleId = role.id
      const { data: res } = await this.$http.get(`rights/tree`)
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.$message.success('获取所有权限成功')
      this.rightsList = res.data
      //把对应角色的信息(包括里面的被选中的三级菜单项)传给getleafkeys函数
      //通过getleafkey函数, 把被选择的三级菜单项返回给树形控件所绑定的数组中
      this.getLeafKeys(role, this.checkedKeys)
      this.assignVisible = true
    },

    //把对应角色的三级菜单的被选择项的id传给树形控件所绑定的数组
    getLeafKeys(node, arr) {
      //如果是三级菜单, 就把三级菜单里面的被选中的项的id值给arr数组
      if (!node.children) {
        return arr.push(node.id)
      }
      //如果有children属性, 说明不是三级权限, 要递归调用

      node.children.forEach((element) => {
        this.getLeafKeys(element, arr)
      })
    },

    //分配权限面板关闭的时候
    assignClosed() {
      this.checkedKeys = []
    },
    //给角色授权
    async confirmAssign() {
      const idArr = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys()
      ]
      const idList = idArr.join(',')
      const {data: res } = await this.$http.post(`roles/${this.currentRoleId}/rights`, {
        rids: idList
      })
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.$message.success('角色授权成功')
      this.assignVisible = false
      this.getUserList()
    },
  },
}
</script>

<style scoped lang="less">
.el-tag {
  margin: 7px;
}

.center {
  display: flex;
  align-content: center;
}
</style>
